import React, { Fragment, PureComponent } from 'react'
// import PropTypes from 'prop-types'
import { connect } from 'dva'
import { stringify } from 'qs';
// import request from '@sc/request'
import { Modal, Row, Col, Card, Button, Skeleton, Table, Collapse, Form, Input, Select, Spin } from 'antd'
import OrgModalForm from "./OrgModalForm"
import ChgOrgModalForm from "./ChgOrgModalForm"
import PromiseModalForm from "./PromiseModalForm"
import UserJoinDepartment from "./UserJoinDepartment"
import './index.less'

const confirm = Modal.confirm;
const { Meta } = Card;
const FormItem = Form.Item;
const Option = Select.Option


@connect(({ loading, dispatch, app, orgInsider }) => ({
  app: app,
  orgInsider: orgInsider,
  reloading: loading.effects['orgInsider/getOrganizaInsider'],
  userloading: loading.effects['orgInsider/getInsiderUserList'],
  addloading: loading.effects['orgInsider/addOrganizaInsider'],
  editloading: loading.effects['orgInsider/editOrganizaInsider'],
  chgloading: loading.effects['orgInsider/changeUserDeptRel'],
  joinloading: loading.effects['orgInsider/inviteUserJoinOrg'],
  setloading: loading.effects['orgInsider/setUserRole'],
}))
@Form.create()
class OrgInsiders extends PureComponent {
  state = {
    visiable: false,
    currentData: "",
    modalType: '',
  }

  componentDidMount() {
    const { dispatch, app: { urlParams } } = this.props
    new Promise((resolve) => {
      dispatch({
        type: 'orgInsider/getOrganizaInsider',
        payload: {
          resolve,
          orgId: urlParams
        }
      })
    }).then((code) => {
      if (code === 1) {
        dispatch({
          type: 'orgInsider/getInsiderUserList',
          payload: {
            orgId: urlParams,
            deptId: null
          }
        })
      }
    })
  }

  switchType = (type) => {
    switch (type) {
      case "division":
        return { url: "orgInsider/addOrganizaInsider", type: "division" }
        break;
      case "subdivision":
        return { url: "orgInsider/addOrganizaInsider", type: "subdivision" }
        break;
      case "edit":
        return { url: "orgInsider/editOrganizaInsider", type: "edit" }
        break;
      case "change":
        return { url: "orgInsider/changeUserDeptRel", type: "change" }
        break;
      case "promise":
        return { url: "orgInsider/setUserRole", type: "promise" }
        break;
      case "join":
        return { url: "orgInsider/inviteUserJoinOrg", type: "join" }
        break;
      case "delDivison":
        return { url: "orgInsider/deleteOrganizaInsider", type: "delDivison" }
        break;
      case "delUser":
        return { url: "orgInsider/deleteDeptUserRel", type: "delUser" }
        break;
    }
  }

  organization = (type, data) => {//根据id查询部门
    const { dispatch, app: { urlParams } } = this.props
    // console.log(`currentData---------->`, type, data)
    if (type === "promise") {
      dispatch({
        type: "orgInsider/getRolesByOrgId",
        payload: {
          userId: data.uid || data.id,
          orgId: data.orgId || urlParams
        }
      })
    }
    if (data.children) {
      dispatch({
        type: "orgInsider/searchOrganizaInsider",
        payload: {
          id: data.id,
          orgId: data.orgId
        }
      })
    }
    this.setState({
      currentData: data || "",
      modalType: type,
      visiable: true,
    })
  }
  handleOk = (e) => {//表单提交按钮
    e.preventDefault();
    const { modalType, currentData } = this.state
    const { dispatch, orgInsider: { orgDepartmentInfo }, app: { urlParams, singleOriginal },
      form: { validateFieldsAndScroll, resetFields } } = this.props
    validateFieldsAndScroll((error, value) => {
      if (error) return
      const dispatchType = this.switchType(modalType)
      new Promise((resolve) => {
        dispatch({
          type: dispatchType.url,
          payload: {
            resolve,
            ...value,
            orgId: orgDepartmentInfo.orgId || currentData.orgId || singleOriginal.id,
            id: dispatchType.type === "edit" ? orgDepartmentInfo.id : null,
            parentId: dispatchType.type === "subdivision" ? orgDepartmentInfo.id : null,
            userId: dispatchType.type === "join" ? value.userId :
              dispatchType.type === "promise" ? currentData.uid || currentData.id :
                dispatchType.type === "change" ? currentData.uid || currentData.id : null,
            deptId: dispatchType.type === "change" ? currentData.deptId :
              dispatchType.type === "join" ? value.deptId : null,
            applyFlag: dispatchType.type === 'join' ? 2 : null,
          }
        })
      }).then((code) => {
        this.setState({ visiable: false })
        resetFields();
        if (code === 1) {
          dispatch({
            type: 'orgInsider/getOrganizaInsider',
            payload: { orgId: orgDepartmentInfo.orgId || currentData.orgId || singleOriginal.id }
          })
        }
      })
    })
  }
  handleCancel = () => {//表单取消按钮
    const { form: { resetFields } } = this.props
    this.setState({
      visiable: false,
    });
    resetFields();
  }

  showDeleteConfirm = (type, data) => {//删除弹窗 部门or人员
    const dispatchType = this.switchType(type)
    const { dispatch } = this.props
    confirm({
      title: '确定要删除吗?',
      content: '删除组织后改组织下的公司和部门、人员会xxx，你还要删除吗？',
      okText: '删除',
      okType: 'danger',
      cancelText: '取 消',
      onOk() {
        new Promise((resolve) => {
          dispatch({
            type: dispatchType.url,
            payload: {
              resolve,
              departmentId: dispatchType.type === "delDivison" ? data.id : null,
              userId: dispatchType.type === "delUser" ? parseInt(data.uid) : null,
              deptId: dispatchType.type === "delUser" ? data.deptId : null,
              orgId: dispatchType.type === "delUser" ? data.orgId : null,
            }
          })
        }).then((code) => {
          if (code === 1) {
            dispatch({
              type: 'orgInsider/getOrganizaInsider',
              payload: { orgId: data.orgId }
            })
          }
        })
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }

  onExpand = (boolean, record) => {//展开树形图标
    const { dispatch } = this.props
    if (boolean) {
      dispatch({
        type: 'orgInsider/getInsiderUserList',
        payload: {
          orgId: record.orgId,
          deptId: record.id
        }
      })
    }
  }
  modalTitle = (modalType) => {
    const { currentData } = this.state
    const { app: { singleOriginal } } = this.props
    switch (modalType) {
      case "division":
        return <span>创建一级部门</span>
        break;
      case "subdivision":
        return <span>创建<span style={{ color: '#067dc6' }}>{currentData.name || "XXX"}</span>下的子部门</span>
        break;
      case "edit":
        return <span>编辑<span style={{ color: '#067dc6' }}>{currentData.name || "XXX"}</span>部门</span>
        break;
      case "change":
        return <span>更换<span style={{ color: '#067dc6' }}>{currentData.name || "XXX"}</span>的所属部门</span>
        break;
      case "promise":
        return <span><span style={{ color: '#067dc6' }}>{currentData.name || "XXX"}</span>的权限设置</span>
        break;
      case "join":
        return <span>邀请用户加入到<span style={{ color: '#067dc6' }}>{singleOriginal.name || "XXX"}</span>组织下的部门</span>
        break;
    }
  }

  render() {
    const { visiable, modalType, currentData } = this.state;
    const { reloading, userloading, addloading, editloading, chgloading, joinloading, setloading, orgInsider: { orgDepartmentList }, form } = this.props;
    const columns = [
      {
        title: '名称',
        // dataIndex: 'name',
        key: 'name',
        width: '80%',
        render: (record) => {
          // console.log(`???????????`,text, record)
          if (record.children) {
            return (<span>
              {record.name}  ({record.userCount})
          </span>)
          }
          return (<span>
            {record.name}  ({record.mobile})
          </span>)
        }
      }, {
        dataIndex: '',
        key: 'x',
        render: (record) => {
          if (record.children) {
            return (<Col style={{ textAlign: 'right' }}>
              <a onClick={e => this.organization("edit", record)} style={{ marginRight: "10px" }}>编辑</a>
              <a onClick={e => this.organization("subdivision", record)} style={{ marginRight: "10px" }}>创建子部门</a>
              <a onClick={e => this.showDeleteConfirm("delDivison", record)} style={{ color: "#f5222d" }}>删除</a>
            </Col>)
          }
          return (<Col style={{ textAlign: 'right' }}>
            <a onClick={e => this.organization("promise", record)} style={{ marginRight: "10px" }}>权限设置</a>{/*  onClick={e => this.organization("promise", record)} */}
            <a onClick={e => this.organization("change", record)} style={{ marginRight: "10px" }}>{record.group === null ? "加入部门" : "更换部门"}</a>
            {record.group === null ? "" : <a onClick={e => { this.showDeleteConfirm("delUser", record) }} style={{ color: "#f5222d" }}>删除</a>}
          </Col>)
        }
      },
    ];

    // console.log(`orgDepartmentList---->`, orgDepartmentList)
    return (
      <Fragment>
        <Card
          style={{ marginTop: 16 }}
          type="inner"
          title="组织内的部门及人员">
          <Skeleton active title={false} loading={!!reloading}>
            <Meta
              description={<Row>
                <Col style={{ marginBottom: '10px' }}>
                  <Button type="primary" onClick={e => this.organization("division", "")} style={{ marginRight: "10px" }}> 创建一级部门 </Button>
                  <Button onClick={e => this.organization("join", "")} > 邀请加入 </Button>
                </Col>
                <Col>
                  {orgDepartmentList && <Spin
                    size="small"
                    spinning={!!userloading}
                    tip="加载中...">
                    <Table
                      rowKey='id'
                      showHeader={false}
                      pagination={false}
                      onRow={this.onRow}
                      onExpand={this.onExpand}
                      columns={columns}
                      dataSource={orgDepartmentList}
                    />
                  </Spin>}
                </Col>
              </Row>}
            />
          </Skeleton>
        </Card>

        <Modal
          title={this.modalTitle(modalType)}
          visible={visiable}
          onOk={this.handleOk}
          confirmLoading={modalType === "change" ? !!chgloading :
            modalType === "promise" ? !!setloading :
              modalType === "join" ? !!joinloading :
                modalType === "edit" ? !!editloading : !!addloading}
          onCancel={this.handleCancel}>
          {modalType === "change" ?
            <ChgOrgModalForm form={form} modalType={modalType} dataSource={currentData} /> :
            modalType === "promise" ?
              <PromiseModalForm form={form} modalType={modalType} dataSource={currentData} /> :
              modalType === "join" ?
                <UserJoinDepartment form={form} modalType={modalType} /> : <OrgModalForm form={form} modalType={modalType} />}
        </Modal>
      </Fragment >
    )
  }
}


export default OrgInsiders;
